package com.source.module_kotlin_library.activity

import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.support.constraint.ConstraintLayout
import android.support.v7.app.AppCompatActivity
import android.util.Base64
import android.view.View
import android.view.ViewStub
import android.widget.ProgressBar
import android.widget.TextView
import com.source.module_kotlin_library.R
import com.source.module_kotlin_library.bean.User2
import com.source.module_kotlin_library.http.HttpService
import com.source.module_kotlin_library.utils.KTToastUtils
import com.source.module_kotlin_library.utils.showToast
import kotlinx.android.synthetic.main.activity_kotlin_lesson.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.net.URLDecoder
import kotlin.coroutines.EmptyCoroutineContext

class KotlinLessonActivity : AppCompatActivity() {
    private val castList = arrayOf(
            "11",
            "22",
            "33"
    )
    private val arraylist = arrayOf(1, 2, 3)
    private val intlist = intArrayOf(1, 2, 3)
    private val objectArrayList = arrayListOf<Int>(1, 2, 3, 4, 5, 6)
    private lateinit var tvContent: TextView


    companion object {
        const val TIP_ERROR = "操作失败"

        /**
         * 启动activity
         */
        fun startActivity(context: Context): Unit {
            var intent = Intent()
            intent.setClass(context, KotlinLessonActivity::class.java)
            context.startActivity(intent)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_lesson)

        initView()

        showToast(this, "hello world")
        KTToastUtils.showToast(this, "hello your")
        var arrayListOf = arrayListOf<Int>(1, 2, 3, 4, 5)
//        var arrayListOf = ArrayList<Int>()
        arrayListOf.forEach { i: Int ->
            println("内容：${i}")
        }

        for (it in 0 until (arrayListOf.size)) {
            println("position：${it}，内容：${arrayListOf[it]}")
        }


        val user2 = User2(null, "", "verifyCode")
        val userCopy = user2.copy()
        println(user2 === userCopy)
        println(user2.username ?: "内容为null")
        var passwordcopy = user2.password ?: "内容为空字符串"
        println("内容为：${passwordcopy}")
        println("username是否为空：${user2.username.isNullOrEmpty()}")
        println("password是否为空：${user2.password.isNullOrEmpty()}")

        println(String(Base64.decode("ezEyM30=", Base64.DEFAULT)))
        println(String(Base64.decode("eyJjYXJHcm91cE5hbWUiOiIlRTglQkQlQTYlRTklOTglOUYxIiwiY2FyR3JvdXBTZXJpYWwiOjEsImNhck5hbWUiOiIyJUU1JThGJUI3JUU4JUJEJUE2IiwiY2FyU2VyaWFsIjoyLCJjYXJUeXBlIjoxLCJsb2NsU2VyaWFsIjo2LCJsb2NOYW1lIjoiJUU5JUFBJThDJUU2JTk0JUI2JUU5JTlCJTg2JUU3JUJCJTkzJUU3JTgyJUI5NiJ9", Base64.URL_SAFE)))
        println(URLDecoder.decode("%E8%BD%A6%E9%98%9F1", "utf-8"))
        println(URLDecoder.decode("", "utf-8"))
        println(URLDecoder.decode("123", "utf-8"))
        println(URLDecoder.decode("%E8%BD%A6%E9%98%9F1", "utf-8"))
        println(URLDecoder.decode("2%E5%8F%B7%E8%BD%A6", "utf-8"))
        println(URLDecoder.decode("%E9%AA%8C%E6%94%B6%E9%9B%86%E7%BB%93%E7%82%B96", "utf-8"))
        println(String(Base64.decode("eyJjYXJHcm91cE5hbWUiOiLovabpmJ8xIiwiY2FyR3JvdXBTZXJpYWwiOjEsImNhck5hbWUiOiLovabovoblkI3np7AiLCJjYXJTZXJpYWwiOjIsImNhclR5cGUiOjEsImxvY2xTZXJpYWwiOjYsImxvY05hbWUiOiLljJfkuqzluILopb/ln47ljLoiLCJzbG5EZXZpY2VDb2RlIjoiMTIzIn0=", Base64.DEFAULT)))
        println(String(Base64.encode("{\"carGroupName\":\"车队1\",\"carGroupSerial\":1,\"carName\":\"车辆名称\",\"carSerial\":2,\"carType\":1,\"loclSerial\":6,\"locName\":\"北京市西城区\",\"slnDeviceCode\":\"123\"}".toByteArray(), Base64.DEFAULT)))
        println(String(Base64.decode(String(Base64.encode("{\"carGroupName\":\"车队1\",\"carGroupSerial\":1,\"carName\":\"车辆名称\",\"carSerial\":2,\"carType\":1,\"loclSerial\":6,\"locName\":\"北京市西城区\",\"slnDeviceCode\":\"123\"}".toByteArray(), Base64.DEFAULT)), Base64.DEFAULT)))
        println(URLDecoder.decode("%E9%97%AD%E7%8E%AF%E5%A4%96-%E6%9C%BA%E5%8A%A8%E5%A4%84%E7%AA%81-%E7%89%B9%E8%AD%A6%E6%AD%A6%E8%A3%85%E5%A4%84%E7%AA%81%28%E9%97%AD%E7%8E%AF%E5%A4%96%29", "utf-8"))

    }

    /**
     * 将Ascii转换成中文字符串
     */

    fun initView() {
        tvContent = findViewById<TextView>(R.id.tvContent)

        var viewStub = findViewById<ViewStub>(R.id.emptyView)

        var btnClick: ConstraintLayout = findViewById(R.id.btnClick)
        val progressBar = btnClick.findViewById<ProgressBar>(R.id.progressBar)
        btnClick?.apply {
            setOnClickListener {
                KTToastUtils.showToast(this@KotlinLessonActivity, "click")

                showEmpty(viewStub)
            }
        }

        Handler().postDelayed({
            progressBar?.visibility = View.GONE
        }, 2000)

//        val emptyView: ViewStub = findViewById(R.id.emptyView)

        val coroutineScope = CoroutineScope(EmptyCoroutineContext)
        coroutineScope.launch(Dispatchers.IO) {
            //TODO:耗时操作
            println("Thread-Name1：${Thread.currentThread().name}")
            launch(Dispatchers.Main) {
                println("Thread-Name2：${Thread.currentThread().name}")
                launch(Dispatchers.IO) {
                    //todo:耗时操作
                    println("Thread-Name3：${Thread.currentThread().name}")
                    launch(Dispatchers.Main) {
                        println("Thread-Name4：${Thread.currentThread().name}")
                    }
                }
            }
        }
        coroutineScope.launch(Dispatchers.Main) {
            val dd = withContext(Dispatchers.IO) {
                //todo:耗时操作
                println("withContext")
                println("Thread-Name5：${Thread.currentThread().name}")
                Thread.sleep(2000)
            }
//            val image = getImage()

            println("update ui")
            println("Thread-Name6：${Thread.currentThread().name}")

            downFile()

        }

        println("---------------------------------------------------------------------------------")


    }


    suspend fun getImage() = withContext(Dispatchers.IO) {
        println("getImage work in io")
        Thread.sleep(2000)
        //OK设置请求超时时间，读取超时时间
        val client = OkHttpClient
                .Builder()
                .connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
                .build()

        val retrofit = Retrofit
                .Builder()
                .client(client)
                .baseUrl("https://blogimages.jspang.com/")
//                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        retrofit?.let {
            it.create(HttpService::class.java)
                    .getImage("blogtouxiang1.jpg")
                    .subscribe({
                        println("responsebody-------------${it.string()}")
                        img.setImageBitmap(BitmapFactory.decodeStream(it.byteStream()))
                    }, {
                        println("error----------${it.message}")
                    }, {
                        println("complete")
                    })
        }
    }

    suspend fun downFile() {
        withContext(Dispatchers.IO) {

            //OK设置请求超时时间，读取超时时间
            val client = OkHttpClient
                    .Builder()
                    .connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
                    .readTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
                    .build()

            val retrofit = Retrofit
                    .Builder()
                    .baseUrl("https://blogimages.jspang.com/")
                    .client(client)
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build()

            retrofit.create(HttpService::class.java)
                    .downFile("blogtouxiang1.jpg")
                    .enqueue(object : Callback<ResponseBody> {
                        override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
//                            TODO("Not yet implemented"
                            println(response.message())
                            img.setImageBitmap(BitmapFactory.decodeStream(response.body()?.byteStream()))
//                            bitmap = BitmapFactory.decodeStream(response.body()?.byteStream())

                        }

                        override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
//                            TODO("Not yet implemented")
                            println(t.message)
                        }
                    })
        }
    }

    /**
     * 获取数据失败时展示
     */
    fun showEmpty(viewStub: ViewStub) {
        val inflate = viewStub?.inflate()
        inflate?.let {
            it.visibility = View.VISIBLE
            val tvDes = findViewById<TextView>(R.id.tvDes)
            tvDes?.let { it ->
                it.text = "服务繁忙"
            }
        }
    }
}